package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.common.util.AESUtil;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.RuXiaoYuanUtil;
import com.block.db.entity.ApplicationInfo;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantDataPushInfo;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 如小愿回调
 */
@Service
public class RuXiaoYuanApiBService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;
    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;

    @Resource
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        long time = System.currentTimeMillis();

        String queryUrl = pushApiKeyParam.getCheckUrl();
        String channelId = pushApiKeyParam.getApiCode();//请求来源
        String secret = pushApiKeyParam.getApiSecret();
        String priKey = pushApiKeyParam.getApiKey();
        String mobileMd5 = memberSourceInfo.getMobileMd5();

        String sign = SecureUtil.md5(mobileMd5 + time).toLowerCase();

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("source", channelId);
        paramMap.put("sign", sign);

        HashMap<String, Object> bizMap = new HashMap<>();
        bizMap.put("phone",memberSourceInfo.getMobileMd5().toLowerCase());
        bizMap.put("ip", RuXiaoYuanUtil.getUserIp(memberSourceInfo.getReqIp()));
        bizMap.put("age",RuXiaoYuanUtil.getUserAge(memberSourceInfo.getAge()));
        bizMap.put("sex",RuXiaoYuanUtil.getUserSex(memberSourceInfo.getSex()));
        bizMap.put("amount",RuXiaoYuanUtil.getLoanAount(memberSourceInfo.getLoanAmount()));
        bizMap.put("provinceName",memberSourceInfo.getProvince());
        String city = memberSourceInfo.getCity();
        if (StrUtil.endWith(city, "市")) {
            city = memberSourceInfo.getCity().substring(0, memberSourceInfo.getCity().length() - 1);
        }
        bizMap.put("cityName",city);
        bizMap.put("occupation",RuXiaoYuanUtil.getjob(memberSourceInfo.getGongzuo()));
        bizMap.put("accumulation",RuXiaoYuanUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("social",RuXiaoYuanUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        bizMap.put("house",RuXiaoYuanUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("car",RuXiaoYuanUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("sesame",RuXiaoYuanUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("insureId",RuXiaoYuanUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("overdue",RuXiaoYuanUtil.getyuqi(memberSourceInfo.getYuqi()));
        bizMap.put("huabei",RuXiaoYuanUtil.gethuabei(memberSourceInfo.getHuabei()));
        bizMap.put("baitiao",RuXiaoYuanUtil.getbaitiao(memberSourceInfo.getBaitiao()));
        bizMap.put("t",time);
        String s = JSON.toJSONString(bizMap);
        String dataAes = null;
        try {
            dataAes = AESUtil.encryptFiveBase64(s, secret, priKey);
        } catch (Exception e) {
            e.printStackTrace();
        }

        paramMap.put("data", dataAes);

        log.info("【如小愿下游url回调】撞库开始【queryUrl】{}【paramMap】{}【bizMap】{}", queryUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【如小愿下游url回调】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);

        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "|" + msg);
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (code == 200) {
            JSONObject jsonObject1 = resultObject.getJSONObject("data");
            String checkOrderNo = jsonObject1.getString("checkOrderNo");
            JSONArray protocolList = jsonObject1.getJSONArray("protocolList");
            for (int i=0;i<protocolList.size();i++){
                String url = protocolList.getJSONObject(i).getString("url");
                extJson.put("url",url);
                extJson.put("checkOrderNo",checkOrderNo);
            }
            pushApiResult.setPushSuccess(true);
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setOrderNo(orderNo);
        pushApiResult.setOutOrderNo(orderNo);

        long time = System.currentTimeMillis();

        String checkOrderNo = extJson.getString("checkOrderNo");
        String url = extJson.getString("url");

        String requestUrl = pushApiKeyParam.getRegisterUrl();
        String channelId = pushApiKeyParam.getApiCode();
        String secret = pushApiKeyParam.getApiSecret();
        String priKey = pushApiKeyParam.getApiKey();
        String mobile = memberSourceInfo.getMobile();

        String sign = SecureUtil.md5(mobile + time).toLowerCase();

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("source", channelId);
        paramMap.put("sign", sign);

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("phone",memberSourceInfo.getMobile());
        bizMap.put("name",memberSourceInfo.getRealname());
        bizMap.put("ip", RuXiaoYuanUtil.getUserIp(memberSourceInfo.getReqIp()));
        bizMap.put("checkOrderNo", checkOrderNo);
        bizMap.put("orderNo", orderNo);
        bizMap.put("userProtocol", url);
        bizMap.put("age",RuXiaoYuanUtil.getUserAge(memberSourceInfo.getAge()));
        bizMap.put("sex",RuXiaoYuanUtil.getUserSex(memberSourceInfo.getSex()));
        bizMap.put("amount",RuXiaoYuanUtil.getLoanAount(memberSourceInfo.getLoanAmount()));
        bizMap.put("provinceName",memberSourceInfo.getProvince());
        String city = memberSourceInfo.getCity();
        if (StrUtil.endWith(city, "市")) {
            city = memberSourceInfo.getCity().substring(0, memberSourceInfo.getCity().length() - 1);
        }
        bizMap.put("cityName",city);
        bizMap.put("occupation",RuXiaoYuanUtil.getjob(memberSourceInfo.getGongzuo()));
        bizMap.put("accumulation",RuXiaoYuanUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("social",RuXiaoYuanUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        bizMap.put("house",RuXiaoYuanUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("car",RuXiaoYuanUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("sesame",RuXiaoYuanUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("insureId",RuXiaoYuanUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("overdue",RuXiaoYuanUtil.getyuqi(memberSourceInfo.getYuqi()));
        bizMap.put("huabei",RuXiaoYuanUtil.gethuabei(memberSourceInfo.getHuabei()));
        bizMap.put("baitiao",RuXiaoYuanUtil.getbaitiao(memberSourceInfo.getBaitiao()));
        bizMap.put("t",time);
        String s = JSON.toJSONString(bizMap);
        String dataAes = null;
        try {
            dataAes = AESUtil.encryptFiveBase64(s, secret, priKey);
        } catch (Exception e) {
            e.printStackTrace();
        }

        paramMap.put("data", dataAes);

        log.info("【如小愿下游双授权】导单开始【queryUrl】{}【bizMap】{}【paramMap】{}", requestUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);
        log.info("【如小愿下游双授权】导单结束【result】{}", resultObject.toJSONString());


        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "|" + msg);
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);


        if (StrUtil.equals(String.valueOf(code),"200")) {
            JSONObject jsonObject1 = resultObject.getJSONObject("data");
            String url1 = jsonObject1.getString("url");
            pushApiResult.setApproveUrl(url1);
            pushApiResult.setPushSuccess(true);
            return pushApiResult;
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }


    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();

        JSONObject jsonObject = JSON.parseObject(paramContent);
        String orderNo = jsonObject.getString("orderNo");

        noticeParamDTO.setOutFlag(true);

        noticeParamDTO.setSettleFlag(true);
        noticeParamDTO.setOutOrderNo(orderNo);
        noticeParamDTO.setStatus(PushStatusEnum.SUCCESS.getValue());
        noticeParamDTO.setQueryResult(paramContent);

        MerchantDataPushInfo entityByOutOrderNoLock = merchantDataPushInfoMapper.getEntityByOutOrderNoLock(infoId, String.valueOf(orderNo));
        noticeParamDTO.setMerchantDataPushInfo(entityByOutOrderNoLock);

        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 200);
        jsonObject.put("msg", "成功");
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }


}
